"use client";
import { useEffect, useState } from "react";
import { ethers } from "ethers";
import { motion, AnimatePresence } from "framer-motion";

import Header from "./components/Header";
import Create from "./components/Create";
import Bet from "./components/Bet";
import Resolve from "./components/Resolve"; // 新增的组件
import abi from "./abis/Market.json";
import config from "./config.json";

export default function Home() {
  const [provider, setProvider] = useState(null);
  const [account, setAccount] = useState(null);
  const [market, setMarket] = useState(null);
  const [fee, setFee] = useState("");

  const [issues, setIssues] = useState([]);
  const [issue, setIssue] = useState({});

  const [showCreate, setShowCreate] = useState(false);
  const [showBet, setShowBet] = useState(false);
  const [showResolve, setShowResolve] = useState(false); // Resolve 弹窗状态
  const [isAdmin,setIsAdmin] = useState(false);

  const [currentPage, setCurrentPage] = useState(1);
  const issuesPerPage = 6;

  const loadBlockchainData = async () => {
    try {
      let provider;
      if (window.ethereum == null) {
        console.log("MetaMask not installed; using read-only defaults");
        provider = ethers.getDefaultProvider();
      } else {
        provider = new ethers.BrowserProvider(window.ethereum);
      }
      setProvider(provider);

      const network = await provider.getNetwork();
      const address = config[network.chainId]?.market?.address;

      if (!address) {
        console.error("Contract not deployed on this network");
        return;
      }

      const market = new ethers.Contract(address, abi, provider);
      setMarket(market);

      const signer = await provider.getSigner();
      if(market){
        const owner = await market.owner();
        const isAdmin = signer.address == owner
        setIsAdmin(isAdmin);
      }else{
        console.error("Contract not deployed on this network");
        setIsAdmin(false);
      }
      
      const fee = await market.fee();
      setFee(Number(ethers.formatEther(fee)));

      const totalIssues = await market.getAllIssues();
      const formattedIssues = totalIssues.map((issue, index) => ({
        id: index,
        description: issue.description,
        options: issue.options,
        deadline: new Date(Number(issue.deadline)).toLocaleString(),
        pool: ethers.formatEther(issue.pool),
        isResolved: issue.isResolved,
        winningOption: issue.winningOption,
      }));

      setIssues(formattedIssues.reverse());
    } catch (error) {
      console.error("Error loading blockchain data:", error);
    }
  };

  useEffect(() => {
    loadBlockchainData();
  }, []);

  const toggleCreate = () => setShowCreate(!showCreate);

  const toggleBet = (selectedIssue) => {
    setIssue(selectedIssue);
    setShowBet(!showBet);
  };

  const toggleResolve = (selectedIssue) => {
    setIssue(selectedIssue);
    setShowResolve(!showResolve);
  };

  // Pagination logic
  const indexOfLastIssue = currentPage * issuesPerPage;
  const indexOfFirstIssue = indexOfLastIssue - issuesPerPage;
  const currentIssues = issues.slice(indexOfFirstIssue, indexOfLastIssue);

  const paginate = (pageNumber) => setCurrentPage(pageNumber);

  return (
    <div className="bg-gray-900 min-h-screen text-white font-pixel">
      <Header account={account} setAccount={setAccount} />

      <main className="p-8">
        {!showCreate && !showBet && !showResolve && (
          <>
            <div className="flex justify-center mb-6">
              <button
                onClick={market && account && toggleCreate}
                className="px-8 py-4 border-4 border-pink-400 bg-gray-800 shadow-[6px_6px_0_#ff00ff] text-xl hover:bg-pink-500 transition"
              >
                {!market ? "[ contract not deployed ]" : !account ? "[ please connect wallet ]" : "[ create Issue ]"}
              </button>
            </div>

            <div className="grid grid-cols-1 md:grid-cols-2 gap-8">
              {account &&
                market &&
                currentIssues.map((issue, index) => (
                  <div
                    key={index}
                    className="p-6 border-4 border-pink-400 bg-gray-800 shadow-[6px_6px_0_#ff00ff] transition"
                  >
                    <h3 className="text-2xl font-bold text-pink-300">{issue.description}</h3>
                    <div className="mt-2">
                      {issue.options.map((option, optionIndex) => (
                        <p key={optionIndex} className="text-white text-lg">- {option}</p>
                      ))}
                    </div>
                    <p className="text-yellow-300 mt-4">Deadline: {issue.deadline}</p>
                    <p className={`mt-2 text-lg ${issue.isResolved ? "text-green-400" : "text-red-400"}`}>
                      {issue.isResolved ? "Resolved" : "Unresolved"}
                    </p>
                    <div className="flex justify-between mt-4">
                      <button
                        onClick={() => toggleBet(issue)}
                        className="px-4 py-2 bg-pink-400 hover:bg-pink-500 transition"
                      >
                        Bet
                      </button>
                      {isAdmin && !issue.isResolved &&
                      <button
                        onClick={() => toggleResolve(issue)}
                        className="px-4 py-2 bg-blue-400 hover:bg-blue-500 transition"
                      >
                        Resolve
                      </button>
                      }
                    </div>
                  </div>
                ))}
            </div>

            {/* Pagination */}
            <div className="flex justify-center mt-8">
              {Array.from({ length: Math.ceil(issues.length / issuesPerPage) }, (_, i) => (
                <button
                  key={i}
                  onClick={() => paginate(i + 1)}
                  className={`mx-2 px-4 py-2 border-2 border-pink-400 ${
                    currentPage === i + 1 ? "bg-pink-400 text-white" : "bg-gray-800 text-pink-400"
                  } hover:bg-pink-500 transition`}
                >
                  {i + 1}
                </button>
              ))}
            </div>
          </>
        )}

        {/* Animated Components */}
        <AnimatePresence>
          {showCreate && (
            <motion.div
              initial={{ opacity: 0, y: -50 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -50 }}
              transition={{ duration: 0.3 }}
            >
              <Create toggleCreate={toggleCreate} fee={fee} provider={provider} market={market} />
            </motion.div>
          )}
        </AnimatePresence>

        <AnimatePresence>
          {showBet && (
            <motion.div
              initial={{ opacity: 0, y: -50 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -50 }}
              transition={{ duration: 0.3 }}
            >
              <Bet toggleBet={toggleBet} issue={issue} provider={provider} market={market} />
            </motion.div>
          )}
        </AnimatePresence>

        <AnimatePresence>
          {showResolve && (
            <motion.div
              initial={{ opacity: 0, y: -50 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -50 }}
              transition={{ duration: 0.3 }}
            >
              <Resolve toggleResolve={toggleResolve} issue={issue} provider={provider} market={market} />
            </motion.div>
          )}
        </AnimatePresence>
      </main>
    </div>
  );
}
